package com.koro.controller;

import com.koro.DTO.FindJobInfoDTO;
import com.koro.DTO.JobInfoDTO;
import com.koro.annotation.NoRepeatSubmit;
import com.koro.annotation.ValidateRequestObject;
import com.koro.entity.JobInfo;
import com.koro.service.JobInfoService;
import com.koro.vo.ResponseObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "定时任务管理")
@RestController
@RequestMapping("/quartz")
public class JobInfoController {

    @Autowired
    private JobInfoService jobInfoService;

    @PostMapping("/createJob")
    @ApiOperation(value = "创建定时任务",notes = "创建定时任务")
    public ResponseObject createJob(@RequestBody JobInfoDTO dto) {
        jobInfoService.addCronJob(dto);
        return ResponseObject.ok();
    }


    @GetMapping("/list")
    @ApiOperation(value = "定时任务列表",notes = "创建定时任务列表")
    public ResponseObject<List<JobInfo>> list(FindJobInfoDTO dto) {
        List<JobInfo> sysLogList = jobInfoService.queryList(dto);
        return ResponseObject.ok(sysLogList);
    }

    /**
     * 删除一个任务
     */
    @GetMapping("/delete")
    @NoRepeatSubmit
    @ApiOperation(value = "删除定时任务",notes = "删除定时任务")
    public ResponseObject delete(@RequestParam Long id) {
        jobInfoService.delete(id);
        return ResponseObject.ok();
    }

    @GetMapping("/info")
    @ApiOperation(value = "定时任务信息",notes = "定时任务信息")
    public ResponseObject<JobInfo> info(@RequestParam Long id) {
        return ResponseObject.ok(jobInfoService.findJobById(id));
    }

    /**
     * 任务调度状态修改
     */
    @PostMapping("/updateStatus")
    @NoRepeatSubmit
    @ApiOperation(value = "修改定时任务状态",notes = "修改定时任务状态")
    public ResponseObject changeStatus(@RequestBody JobInfoDTO dto) {
        JobInfo newJob = jobInfoService.findJobById(dto.getJobId());
        newJob.setStatus(dto.getStatus());
        jobInfoService.updateStatus(newJob);
        return ResponseObject.ok();
    }

    /**
     * 任务调度立即执行一次
     */
    @GetMapping("/run")
    @NoRepeatSubmit
    @ApiOperation(value = "立即执行定时任务",notes = "立即执行定时任务")
    public ResponseObject run(@RequestParam Long id) {
        jobInfoService.executeRun(id);
        return ResponseObject.ok();
    }

    /**
     * 修改保存调度
     */
    @PostMapping("/update")
    @ValidateRequestObject
    @NoRepeatSubmit
    @ApiOperation(value = "更新定时任务",notes = "更新定时任务")
    public ResponseObject update(@RequestBody JobInfoDTO dto) {
        jobInfoService.updateJob(dto);
        return ResponseObject.ok();
    }

    /**
     * 校验cron表达式是否有效
     */
    @GetMapping("/checkCronExpressionIsValid")
    @ApiOperation(value = "校验定时任务",notes = "校验定时任务")
    public ResponseObject<Boolean> checkCronExpressionIsValid(@RequestParam String cronExpression) {
        return ResponseObject.ok(jobInfoService.findCheckCronExpressionIsValid(cronExpression));
    }

}

